package top.lshaci.learning.excel;

import cn.hutool.core.io.file.FileNameUtil;
import cn.hutool.core.util.ArrayUtil;
import com.aspose.cells.License;
import com.aspose.cells.PdfSaveOptions;
import com.aspose.cells.Workbook;
import com.aspose.cells.WorksheetCollection;
import lombok.extern.slf4j.Slf4j;

import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.Optional;

/**
 * Excel2Pdf
 *
 * @author liangxu
 */
@Slf4j
public class Excel2Pdf {

    public static void convert(String excelFilePath, String pdfFilePath, int... convertSheets) throws Exception {
        getLicense();
        Workbook workbook = new Workbook(excelFilePath);
        FileOutputStream pdfFos = new FileOutputStream(Optional.ofNullable(pdfFilePath).orElseGet(() -> Excel2Pdf.pdfFilePath(excelFilePath)));
        PdfSaveOptions pdfSaveOptions = new PdfSaveOptions();
        pdfSaveOptions.setOnePagePerSheet(true);
        printSheetPage(workbook, convertSheets);
        workbook.save(pdfFos, pdfSaveOptions);
        pdfFos.flush();
        pdfFos.close();
    }

    private static String pdfFilePath(String excelFilePath) {
        return FileNameUtil.getPrefix(excelFilePath) + ".pdf";
    }

    private static void getLicense() {
        String licenseFilePath = "excel-license.xml";
        try {
            InputStream is = Excel2Pdf.class.getClassLoader().getResourceAsStream(licenseFilePath);
            License license = new License();
            license.setLicense(is);
        } catch (Exception e) {
            log.error("License verify failed!", e);
        }
    }

    /**
     * 隐藏 Workbook 中不需要显示的 sheet 页
     *
     * @param workbook      Excel 解析后的 Workbook
     * @param convertSheets 需要转换的 sheet 页
     */
    private static void printSheetPage(Workbook workbook, int[] convertSheets) {
        if (ArrayUtil.isEmpty(convertSheets)) {
            return;
        }
        WorksheetCollection worksheets = workbook.getWorksheets();
        for (int i = 1; i < worksheets.getCount(); i++) {
            worksheets.get(i).setVisible(false);
        }
        for (int sheet : convertSheets) {
            worksheets.get(sheet).setVisible(true);
        }
    }
}
